package com.straw.hat.common.util;

import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.replace.Replace;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.util.TablesNamesFinder;

import java.io.StringReader;
import java.util.List;

/**
 * @author jianshan@byai.com
 * @date 2021/1/5 8:26 PM
 * describe:
 */
public class SqlUtil {

    private static CCJSqlParserManager pm = new CCJSqlParserManager();

    private static List<String> getTableNames(String sql) throws Exception {
        List<String> tablenames = null;
        TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
        Statement statement = pm.parse(new StringReader(sql));
        if (statement instanceof Select) {
            tablenames = tablesNamesFinder.getTableList((Select) statement);
        } else if (statement instanceof Update) {
            return null;
        } else if (statement instanceof Delete) {
            return null;
        } else if (statement instanceof Replace) {
            return null;
        } else if (statement instanceof Insert) {
            return null;
        }
        return tablenames;
    }


    public static void main(String[] args) throws Exception {
        System.out.println(getTableNames("select * from scene_mb0001"));
    }
}
